package edu.maplef.bookwild.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class StrCharUtil {
	/**
	 * 对整个url进行编码转换
	 * @param srcStr url串
	 * @param enc  编码
	 * @return 
	 */
	public static String URLEncode(String srcStr, String enc) {
		String[] arrayUrl = split(srcStr, "?");
		if (arrayUrl.length <= 1)
			return srcStr;
		String qryStr = arrayUrl[1];
		String[] arrayQryStr = split(qryStr, "&");
		String newQryStr = "";
		for (int i = 0; i < arrayQryStr.length; i++) {
			String param = arrayQryStr[i];
			String[] arrayParam = split(param, "=");
			if (arrayParam.length > 1) {
				try {
					arrayParam[1] = URLEncoder.encode(arrayParam[1], enc);
				} catch (Exception e) {

				}
				arrayQryStr[i] = arrayParam[0] + "=" + arrayParam[1];
			} else
				arrayQryStr[i] = arrayParam[0] + "=";
			newQryStr += arrayQryStr[i] + "&";
		}
		return arrayUrl[0] + "?" + newQryStr;
	}

	/**
	 * @param wholeStr :字符串
	 * @param substr：子串
	 * @return 返回子串在字符串中的个数
	 */
	public static int getSubStringNum(String wholeStr, String substr) {
		int num = 0;
		String temp = wholeStr;
		int i = 0;
		while (temp.indexOf(substr) >= 0) {
			temp = temp.substring(temp.indexOf(substr) + 1);
			i = temp.indexOf(substr) + 1;
			num++;
		}
		return num;
	}

	/**
	 * 获取字符串的前n位
	 * @param srcStr
	 * @param size
	 * @return 
	 */
	public static String getSubstring(String srcStr, int size) {
		if (srcStr == null)
			return null;
		if (size <= 0)
			return "";
		if (size >= srcStr.length())
			return srcStr;
		String result = "";
		result = srcStr.substring(0, size);
		return result;
	}

	/**
	 * 获取字符串的前面或者后面n个字符
	 * @param srcStr
	 * @param size
	 * @param sequence 1：表示前面 -1：表示后面
	 * @return 
	 */
	public static String getSubstring(String srcStr, int size, int sequence) {
		if (srcStr == null)
			return null;
		if (size <= 0)
			return "";
		if (size >= srcStr.length())
			return srcStr;
		String result = "";
		if (sequence == -1)
			result = srcStr.substring(srcStr.length() - size, srcStr.length());
		else
			result = srcStr.substring(0, size);
		return result;
	}

	/**
	 * 把null字符串转换为""
	 * @param srcStr
	 * @return 
	 */
	public static String formatNullStr(String srcStr) {
		if (srcStr == null)
			srcStr = "";
		else if (srcStr.toString().equalsIgnoreCase("null"))
			srcStr = "";
		return srcStr;
	}

	public static String formatNullStr(Object obj) {
		if (obj == null)
			return "";
		else if (obj.toString().equalsIgnoreCase("null"))
			return "";
		return obj.toString();
	}

	/**
	 * 
	 * 转换sql字符串中的'为''
	 * @param srcStr
	 * @return 
	 */
	public static String formatSqlStr(String srcStr) {
		if (srcStr == null)
			return null;
		String destStr = "";
		for (int i = 0; i < srcStr.length(); i++) {
			if (srcStr.substring(i, i + 1).equals("'"))
				destStr += "''";
			else
				destStr += srcStr.substring(i, i + 1);
		}
		return destStr;
	}

	/**
	 * 把字符串根据分割串拆分成数组
	 * @param srcStr
	 * @param delimiter  分割串
	 * @return 
	 */
	public static String[] split(String srcStr, String delimiter) {
		int k = 0;
		ArrayList resultList = new ArrayList();
		while (k >= 0) {
			k = srcStr.indexOf(delimiter);
			if (k >= 0) {
				resultList.add(srcStr.substring(0, k));
			} else {
				break;
			}
			srcStr = srcStr.substring(k + delimiter.length(), srcStr.length());
		}
		resultList.add(srcStr);
		String[] resultArray = new String[resultList.size()];
		for (int i = 0; i < resultList.size(); i++) {
			resultArray[i] = resultList.get(i).toString();
		}
		return resultArray;
	}

	public static final byte NORMAL_SPLIT = 0;//普通分割

	public static final byte FILTER_SAME_SENSECHAR = 1;//不忽略大小写，相同移除

	public static final byte FILTER_SAVE_IGNORE_SENSECHAR = 2;//忽略大小写，相同移除

	public static String[] split(String srcStr, String delimiter,
			byte splitStyle) {
		if (splitStyle == FILTER_SAME_SENSECHAR
				|| splitStyle == FILTER_SAVE_IGNORE_SENSECHAR) {
			int k = 0;
			ArrayList resultList = new ArrayList();
			boolean can = true;
			String temp1 = "";
			while (k >= 0) {
				can = true;
				k = srcStr.indexOf(delimiter);
				if (k >= 0) {
					String temp = srcStr.substring(0, k);
					//检查是否已经有temp字串
					if (resultList != null && resultList.size() >= 1) {
						for (int i = 0; i < resultList.size(); i++) {
							temp1 = resultList.get(i).toString();
							if (splitStyle == FILTER_SAME_SENSECHAR) {
								if (temp1.equals(temp)) {
									can = false;
									break;
								}
							} else if (splitStyle == FILTER_SAVE_IGNORE_SENSECHAR) {
								if (temp1.equalsIgnoreCase(temp)) {
									can = false;
									break;
								}
							}
						}
					}
					if (can)
						resultList.add(temp);
				} else {
					break;
				}
				srcStr = srcStr.substring(k + delimiter.length(), srcStr
						.length());
			}
			String temp = srcStr;
			can = true;
			//检查是否已经有temp字串
			if (resultList != null && resultList.size() >= 1) {
				for (int i = 0; i < resultList.size(); i++) {
					temp1 = resultList.get(i).toString();
					if (splitStyle == FILTER_SAME_SENSECHAR) {
						if (temp1.equals(temp)) {
							can = false;
							break;
						}
					} else if (splitStyle == FILTER_SAVE_IGNORE_SENSECHAR) {
						if (temp1.equalsIgnoreCase(temp)) {
							can = false;
							break;
						}
					}
				}
			}
			if (can)
				resultList.add(temp);
			String[] resultArray = new String[resultList.size()];
			for (int i = 0; i < resultList.size(); i++) {
				resultArray[i] = resultList.get(i).toString();
			}
			return resultArray;
		} else {
			return split(srcStr, delimiter);
		}
	}

	/**
	 * 合并字符串数组为一个串
	 * @param str 字符串数组
	 * @return 
	 * @param delimiter 隔开字符
	 */
	public static String merge(String[] src, String delimiter,
			boolean ignoreNullStr) {
		String newSrc = "";
		for (int i = 0; i < src.length; i++) {
			if (ignoreNullStr && (src[i] == null || src[i].trim().equals("")))
				continue;
			if (i < src.length - 1)
				newSrc += src[i] + delimiter;
			else
				newSrc += src[i];
		}

		return newSrc;
	}

	/**
	 * 
	 * @param srcStr
	 * @param delChar
	 * @return 
	 */
	public static String delEndZero(String srcStr, char delChar) {
		int i = 0;
		for (i = srcStr.length() - 1; i >= 0; i--) {
			if (srcStr.charAt(i) != delChar)
				break;
		}
		System.out.println(i);
		return srcStr.substring(0, ++i);
	}

	public static long parseLong(String srcStr, long defaultValue, long minValue) {
		long resultValue = defaultValue;
		if (srcStr == null)
			srcStr = "";
		if (srcStr.equals(""))
			return defaultValue;

		try {
			resultValue = Long.parseLong(srcStr);
		} catch (Exception e) {
		}
		if (resultValue <= minValue)
			resultValue = defaultValue;
		return resultValue;
	}

	public static double parseDouble(String srcStr, double defaultValue,
			double minValue) {
		double resultValue = defaultValue;
		if (srcStr.equals(""))
			return defaultValue;

		try {
			resultValue = Double.parseDouble(srcStr);
		} catch (Exception e) {
		}
		if (resultValue <= minValue)
			resultValue = defaultValue;
		return resultValue;
	}

	public static double parseDouble(String srcStr, double defaultValue) {
		double resultValue = defaultValue;
		if (srcStr.equals(""))
			return defaultValue;

		try {
			resultValue = Double.parseDouble(srcStr);
		} catch (Exception e) {
		}

		return resultValue;
	}

	public static int parseInt(String srcStr, int defaultValue, int minValue) {
		int resultValue = defaultValue;
		if (srcStr.equals(""))
			return defaultValue;
		try {
			minValue = Integer.parseInt(srcStr);
		} catch (Exception e) {
			return defaultValue;
		}
		if (resultValue <= minValue)
			resultValue = defaultValue;
		return minValue;

	}

	public static Date parseDate(String strDate, String format)
			throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern(format);
		return sdf.parse(strDate);
	}

	public static Timestamp parseTimestamp(String strTimestamp, String format)
			throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern(format);
		Date date = sdf.parse(strTimestamp);
		sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
		return Timestamp.valueOf(sdf.format(date));
	}

	public static String timestampToStr(Timestamp timestamp, String format)
			throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern(format);
		return sdf.format(timestamp);
	}

	/**
	 * 
	 * @param str 待补0的字符串
	 * @param length　补0后的长度
	 * @return 若参数length<＝参数str的长度，直接返回str,若参数length＞参数str的长度，则在str前面补0
	 * 如addZero("1234",3)="1234", addZero("1234", 8)="00001234"
	 * @throws java.lang.Exception
	 */
	public static String addZero(String str, int length) throws Exception {
		String result = str;
		for (int i = 0; i <= length - str.length() - 1; i++) {
			result = "0" + result;
		}
		return result;
	}

	public static String addStr(String str, int length, String zm)
			throws Exception {
		String result = str;
		int ilen = str.charAt(0) > 128 ? str.length() * 2 : str.length();
		for (int i = 0; i <= length - ilen - 1; i++) {
			result = result + zm;
		}
		return result;
	}

	/**
	 * 
	 * @param source 待补0的Integer
	 * @param length　补0后的长度
	 * @return 若参数length<＝参数str的长度，直接返回str,若参数length＞参数str的长度，则在str前面补0
	 * 如addZero(new Integer(1234),3)="1234", addZero(new Integer(1234), 8)="00001234"
	 * @throws java.lang.Exception
	 */
	public static String addZero(Integer source, int length) throws Exception {
		String ss = source.toString();
		return addZero(ss, length);
	}

	/**
	 * 
	 * @param source 待补0的int
	 * @param length　补0后的长度
	 * @return 若参数length<＝参数str的长度，直接返回str,若参数length＞参数str的长度，则在str前面补0
	 * 如addZero(1234,3)="1234", addZero(1234, 8)="00001234"
	 * @throws java.lang.Exception
	 */
	public static String addZero(int source, int length) throws Exception {
		Integer aa = new Integer(source);
		return addZero(aa, length);
	}

	//cxlh贴加
	public static float parseFloat(String srcStr, float defaultValue) {
		float resultValue = defaultValue;
		if (srcStr.equals(""))
			return defaultValue;

		try {
			resultValue = Float.parseFloat(srcStr);
		} catch (Exception e) {
		}

		return resultValue;
	}

	public static String getNmsFilePath(String path) {
		String res = path;
		if (!res.startsWith("/"))
			res = "/" + res;
		if (!res.endsWith("/"))
			res = res + "/";
		res = res.substring(res.indexOf("/") + 1, res.indexOf("/", 1));
		return res.toLowerCase();
	}

	public static String getNmsPicFilePath(String path) {
		try {
			String str = path;
			if (str.startsWith("/"))
				str = str.substring(1, str.length() - 1);
			String ystr = str.substring(0, str.indexOf("/"));
			str = str.substring(str.indexOf("/") + 1, str.indexOf("/", str
					.indexOf("/") + 1));
			str = StrCharUtil.addZero(str, 2);
			return (ystr + str).toLowerCase();
		} catch (Exception ex) {
			return getNmsFilePath(path);
		}
	}

	//   public static String getNmsMusicFilePath(String path){
	//	   try{
	//	   String str=path;
	//	   if(str.startsWith("/")) str=str.substring(1,str.length()-1);
	//	   str=str.substring(str.indexOf("/")+1);
	//	   String ystr=str.substring(0,str.indexOf("/"));
	//	   str=str.substring(str.indexOf("/")+1,str.indexOf("/",str.indexOf("/")+1));
	//	   str=StrCharUtil.addZero(str,2);	   
	//	   return (ystr+str).toLowerCase();
	//	   }catch(Exception ex){
	//		   return getNmsFilePath(path);
	//	   }
	//   } 
	public static final byte INSTR_IGNORECASE = 0;

	public static final byte INSTR_NOTIGNORECASE = 1;

	public static final byte INSTR_IGNORECASELIKE = 2;

	public static final byte INSTR_NOTIGNORECASETLIKE = 3;

	/**
	 * @param str :用enc分割符组成的串
	 * @param enc
	 * @param mystr：被判断字符串
	 * @param style：判断方式
	 * @param likeStr：当style为INSTR_IGNORECASELIKE或者INSTR_NOTIGNORECASETLIKE才起作用，表示mystr带何字符时表示相似判断
	 * @return
	 */
	public static String inStr(String str, String enc, String mystr,
			byte style, String likeStr) {
		String res = "0";
		if (str == null || str.equals(""))
			return res;
		String[] temp = str.split(enc);
		for (int i = 0; i < temp.length; i++) {
			if (style == INSTR_IGNORECASE) {
				if (temp[i].equalsIgnoreCase(mystr)) {
					res = "1";
					break;
				}
			} else if (style == INSTR_NOTIGNORECASETLIKE) {
				if (temp[i].indexOf(likeStr) >= 0) {
					String tt = Utils.replace(temp[i], "*", "");
					if (mystr.indexOf(tt) >= 0) {
						res = "1";
						break;
					}
				} else {
					if (temp[i].equals(mystr)) {
						res = "1";
						break;
					}
				}
			} else if (style == INSTR_IGNORECASELIKE) {
				if (temp[i].indexOf(likeStr) >= 0) {
					String tt = Utils.replace(temp[i], "*", "");
					if (mystr.toLowerCase().indexOf(tt.toLowerCase()) >= 0) {
						res = "1";
						break;
					}
				} else {
					if (temp[i].equalsIgnoreCase(mystr)) {
						res = "1";
						break;
					}
				}
			} else {
				if (temp[i].equals(mystr)) {
					res = "1";
					break;
				}
			}
		}
		return res;
	}

	public static String inStr(String str, String enc, String mystr,
			boolean ignore) {
		String res = "0";
		if (str == null || str.equals(""))
			return res;
		String[] temp = str.split(enc);
		for (int i = 0; i < temp.length; i++) {
			if (ignore) {
				if (temp[i].equalsIgnoreCase(mystr)) {
					res = "1";
					break;
				}
			} else {
				if (temp[i].equals(mystr)) {
					res = "1";
					break;
				}
			}
		}
		return res;
	}

	/**
	 * 使用正则表达式检验字符串
	 * @param patternString
	 * @param input
	 * @return
	 */
	public static boolean isValidate(String patternString, String input) {
		boolean f = false;
		Pattern pattern = null;
		try {
			pattern = Pattern.compile(patternString);
		} catch (PatternSyntaxException e) {
			System.out.println("Pattern syntax error");
			return false;
		}
		if (input == null || input.equals(""))
			return false;
		Matcher matcher = pattern.matcher(input);
		if (matcher.matches()) {
			f = true;
		} else {
			f = false;
			System.out.println("No match");
		}
		return f;
	}

	/**
	 * 检验UR的合法性
	 * @param str
	 * @return
	 */
	public static boolean isValidateUrl(String str) {
		boolean f = false;
		String pstr = "http://([\\S]+\\.)+[\\S]+(/[\\S ./?%&=]*)?";
		Pattern pattern = Pattern.compile(pstr, Pattern.CASE_INSENSITIVE
				+ Pattern.UNICODE_CASE);
		return isValidate(pstr, str);
	}

	public static String getImgUbbToHtml(String str) {
		try {
			String res = str;
			String pstr = "\\[img\\](.*?)\\[/img\\]";
			Pattern pattern = Pattern.compile(pstr, Pattern.DOTALL);
			Matcher m = pattern.matcher(str);
			int start = 0;
			String temp = "", temp1 = "";
			while (m.find(start)) {
				temp = res.substring(m.start(), m.end());
				temp1 = "<img src=" + temp.substring(5, temp.length() - 6)
						+ ">";
				res = Utils.replace(str, temp, temp1);
				start = m.end();
			}
			return res;
		} catch (Exception ex) {
			ex.printStackTrace();
			return str;
		}
	}

	public static String getLeftRightStr(String cont, String searchStrs, int num) {
		return getLeftRightStr(cont, searchStrs, num, null);
	}

	public static String getLeftRightStr(String cont, String searchStrs,
			int num, String formatSearchStr) {
		String res = "";
		if (searchStrs == null || searchStrs.equals(""))
			return cont;
		String[] strs = split(searchStrs, ",");
		if (strs == null)
			return cont;
		String temp = "";
		for (int i = 0; i < strs.length; i++) {
			if (strs[i] != null && !strs[i].equals("")) {
				Pattern p = Pattern.compile(strs[i]);
				Matcher matcher = null;
				matcher = p.matcher(cont);
				int start = 0;
				int end = 0;
				while (matcher.find(start)) {
					start = matcher.start();
					end = matcher.end();
					// System.out.println(cont.substring(start,end)+":"+"start:"+start+" end:"+end);
					temp = getLeftRightStr(cont, start, end, num,
							formatSearchStr);
					res += temp + ",";
					start = end;
				}
			}
		}
		if (res.length() >= 1)
			res = res.substring(0, res.length() - 1);
		return res;
	}

	public static String getLeftRightStr(String cont, int start, int end,
			int num) {
		return getLeftRightStr(cont, start, end, num, null);
	}

	public static String getLeftRightStr(String cont, int start, int end,
			int num, String formatStr) {
		String s1 = ((start >= num) ? ("...") : "")
				+ cont.substring(((start >= num) ? (start - num) : 0), start);
		String s2 = "";
		if (formatStr != null && !formatStr.equals(""))
			s2 = Utils.replace(formatStr, "[keywordcolor]", cont.substring(
					start, end));
		else
			s2 = cont.substring(start, end);
		String s3 = cont.substring(end,
				(((end + num + 1) >= cont.length()) ? cont.length() : (end
						+ num + 1)))
				+ (((end + num + 1) >= cont.length()) ? "" : "...");
		return s1 + s2 + s3;
	}

	/**
	 * 关键字着色处理
	 * @param keywords
	 * @param str
	 * @return
	 */
	public static String setKeywordColor(String keywords, String str,
			String bgcolor, String fcolor, int fsize) {
		String res = str;
		if (keywords == null || keywords.equals(""))
			return res;
		String[] strs = StrCharUtil.split(keywords, " ");
		for (int i = 0; i < strs.length; i++) {
			Pattern p = Pattern.compile(strs[i], Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(res);
			res = m.replaceAll("<span style=\"background-color: " + bgcolor
					+ "\"><font color=\"" + fcolor + "\" size=\"" + fsize
					+ "\">$0</font></span>");
			//res=Utils.replace(res,strs[i],"<span style=\"background-color: "+SystemCode.getBkgroundColor()+"\"><font size=\""+SystemCode.getFontsize()+"\">"+strs[i]+"</font></span>");	  
		}
		return res;
	}

	//判断字串pos起是否
	public static boolean isInHtmlTag(String str, int pos) {
		String str2 = str.substring(0, pos);
		int i1 = StrCharUtil.getSubStringNum(str2, "<");
		int i2 = StrCharUtil.getSubStringNum(str2, ">");
		if (i1 == i2)
			return false;
		else
			return true;
	}

	//搜索结果加亮
	public static String setKeywordSplitWord(String kw, int ignoreLen,
			String str, int beforeLen, String bgcolor, String fcolor,
			int fontsize) {
		//过滤HTML标签
		str = str.replaceAll("\\<(.*?)\\>", "");
		int start = 0;
		String hstr = "", tstr = "";
		String mstr = "";
		int halfLen = ignoreLen / 2;
		kw = Utils.replace(kw, " ", "|");
		Pattern p = Pattern.compile(kw, Pattern.DOTALL);
		if (str.length() > ignoreLen) {
			hstr = str.substring(0, halfLen);
			tstr = str.substring(str.length() - halfLen, str.length());
			str = str.substring(halfLen, str.length() - halfLen);
			Matcher m = p.matcher(str);
			int prepos = 0;
			while (m.find(start)) {
				int is = m.start();
				int ie = m.end();
				String s = "..."
						+ (str.substring((is - beforeLen < prepos ? is
								: (is - beforeLen)), is))
						+ str.substring(is, ie)
						+ (str.substring(ie,
								(ie + beforeLen) > str.length() ? str.length()
										: (ie + beforeLen))) + "...";
				mstr += s;
				start = ie + beforeLen;
				prepos = ie + beforeLen;
				if (start > str.length())
					break;
			}
			String tempStr = hstr + "..." + mstr + "..." + tstr;
			return setKeywordColor(kw, tempStr, bgcolor, fcolor, fontsize);
		} else {
			//直接替换
			return setKeywordColor(kw, str, bgcolor, fcolor, fontsize);
		}
	}

	/**
	 * 搜索结果加亮
	 * @param kw
	 * @param ignoreLen
	 * @param str
	 * @param beforeLen
	 * @param bgcolor
	 * @param fcolor
	 * @param fontsize
	 * @param kwnum
	 * @return
	 */
	public static String setKeywordSplitWord(String kw, int ignoreLen,
			String str, int beforeLen, String bgcolor, String fcolor,
			int fontsize, int kwnum) {
		if (str == null || str.equals(""))
			return "";
		str = str.replaceAll("\\<(.*?)\\>", "");
		int start = 0;
		String hstr = "";
		String tstr = "";
		String mstr = "";
		int halfLen = ignoreLen / 2;
		kw = Utils.replace(kw, " ", "|");
		Pattern p = Pattern.compile(kw, 32);
		int kwnumber = 0;
		if (str.length() > ignoreLen) {
			hstr = str.substring(0, halfLen);
			tstr = str.substring(str.length() - halfLen, str.length());
			str = str.substring(halfLen, str.length() - halfLen);
			Matcher m = p.matcher(str);
			int prepos = 0;
			while (m.find(start)) {
				if (++kwnumber > kwnum)
					break;
				int is = m.start();
				int ie = m.end();
				String s = "..."
						+ str.substring(is - beforeLen >= prepos ? is
								- beforeLen : is, is)
						+ str.substring(is, ie)
						+ str.substring(ie, ie + beforeLen <= str.length() ? ie
								+ beforeLen : str.length()) + "...";
				mstr = mstr + s;
				start = ie + beforeLen;
				prepos = ie + beforeLen;
				if (start > str.length())
					break;
			}
			String tempStr = hstr + "..." + mstr + "..." + tstr;
			return setKeywordColor(kw, tempStr, bgcolor, fcolor, fontsize);
		} else {
			return setKeywordColor(kw, str, bgcolor, fcolor, fontsize);
		}
	}

	/**
	 * 使用正则表达式进行html过滤（去除各类标签，保留文本内容）
	 * @param inputString
	 * @return
	 */
	public static String tripHTMLTag(String inputString) {
		String htmlStr = inputString; //含html标签的字符串   
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }   
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }   
			String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式   

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); //过滤script标签   

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); //过滤style标签   

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); //过滤html标签   

			textStr = htmlStr;
			textStr = textStr.replaceAll(" ", "");
		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}

		return textStr;//返回文本字符串
	}

	public static String getEqualStr(String str, String substr) {
		String[] strs = Pattern.compile("&").split(str);
		if (strs != null && strs.length > 0) {
			for (int i = 0; i < strs.length; i++) {
				String[] substrs = Pattern.compile("=").split(strs[i]);
				if (substrs != null && substrs.length == 2) {
					if (substrs[0].trim().equalsIgnoreCase(substr)) {
						return substrs[1];
					}
				}
			}
		}
		return "";
	}

	public static String setEqualStr(String str, String substr,
			String substrValue) {
		String[] strs = Pattern.compile("&").split(str);
		if (strs != null && strs.length > 0) {
			for (int i = 0; i < strs.length; i++) {
				String[] substrs = Pattern.compile("=").split(strs[i]);
				if (substrs != null && substrs.length == 2) {
					if (substrs[0].trim().equalsIgnoreCase(substr)) {
						strs[i] = substrs[0] + "=" + substrValue;
					}
				}
			}
		}
		return merge(strs, "&", true);
	}

	/**
	 * 模拟访问某网址URL 
	 * @param strUrl
	 * @return 返回结果String
	 */
	public static String visitURL(String strUrl) {
		URL url = null;
		try {
			url = new URL(strUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		URLConnection conn = null;
		try {
			conn = url.openConnection();
			conn.setDoOutput(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		OutputStreamWriter out;
		try {
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.flush();
			out.close();

		} catch (UnsupportedEncodingException e2) {

			e2.printStackTrace();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		// 接收返回信息
		BufferedReader rd = null;
		try {
			rd = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			return rd.readLine();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return "";
	}

	/**
	 * 获取随机串(0-1000)
	 * 
	 * @return
	 */
	public static String getRandomNum() {
		int num = (int) (Math.random() * 1000);
		return Integer.toString(num);
	}

	/**
	 * 判断字符串是否非空
	 * @param s
	 * @return
	 */
	public static boolean isNullOrEmpty(String s) {
		if (s == null)
			return true;
		else if (s.length() == 0 || s.equals(""))
			return true;
		else
			return false;
	}

	/**
	 * <p>将String[]数组转为String</p>
	 * 如：<br/>
	 * ["a","b"]转化为 "ab"
	 * @param str 
	 * @return
	 */
	public static String parseStringArray(String[] str) {
		StringBuilder sb = new StringBuilder();
		for (String s : str) {
			sb.append(s);
		}
		return sb.toString();
	}

	public static String insertBefore(String str, String which, String targetStr) {
		if (str.indexOf(which) >= 0) {
			int start = str.lastIndexOf(which);
			str = str.substring(0, start) + targetStr + str.substring(start);
		} else {
			str = str + targetStr;
		}
		return str;
	}

	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("\\-", "");
	}

	public static void main(String[] args) {
		//		for(int i=0;i<100;i++)
		//			visitURL("http://b.zhongsou.com/l.dll?DoRequest_r&word=%D6%D0%B9%FA%BF%C6%BC%BC%B4%B4%D2%B5%BC%C6%BB%AE%B4%F3%C8%FC%CD%F8%C2%E7%B9%D8%D7%A2%BD%B1&id=1711248&cid=219822&pn=1");

	}
}
